// src/utils/webviewObjService.js
import btnOptions from '@/pagesB/chum/options.js';
import initLevitatedSphere from '@/pagesB/chum/levitatedSphere.js';
import mediaCache from '@/common/mediacache/mediaCache.js'; // 适配你的实际路径
import menuBtn from '@/pagesB/chum/menuBtn.js';

let webviewObj = null; // Store reference to the webviewObj
let options = null;
let nvMask = null;
let nvImageMenu = null;
let view = null;
let btnXuan = null
// Function to create and show the webviewObj
export function showWebviewObj(data = {}) {
	if (!webviewObj) {
		options = data
		createWebviewObj(); // If webviewObj does not exist, create it
	}else if(options.url != data.url){
		options = data
		webviewObj.loadURL(options.url)
		if(btnXuan){
			btnXuan.close()
			btnXuan = null
		}
	}
	if (!view) {
		// createBtn()
		view = new menuBtn({
		    onClick: (e) => {
				uni.showActionSheet({
					title:getApp().$t('chum.webview.quitTitle'),
					itemList: [
						getApp().$t("common.refresh"),
						getApp().$t("common.suspension"), 
						getApp().$t("common.off")
					],
					success: async(res)=> {
						if(res.tapIndex == 0){
							webviewObj.loadURL(options.url)
						}else if(res.tapIndex == 1){
							webviewObj.hide();
							view.hide();
							if(!btnXuan){
								if(options.icon){
									try {
										const cachedMedia = await mediaCache.loadMedia(options.icon, 'avatar', 'image');
										btnOptions.url = cachedMedia
									} catch (error) {
										btnOptions.url = '_www/static/logo.png'
									}
								}else{
									btnOptions.url = '_www/static/logo.png'
								}
								btnXuan = initLevitatedSphere(btnOptions, clickHandler, true);
							}else{
								btnXuan.show()
							}
						}else if(res.tapIndex == 2){
							if (webviewObj) {
								webviewObj.close();
								webviewObj = null; // Destroy the webviewObjnvMask
								options = null
								view.close();
								view = null;
								btnXuan.close()
								btnXuan = null
							}
						}
					},
					fail: (res)=> {
						console.log(res.errMsg);
					}
				});

			}
		});
	}
	btnXuan && btnXuan.hide()
	webviewObj && webviewObj.show(); // Sho
	view && view.show();
}

// Function to create the webviewObj
function createWebviewObj() {
	const systemInfo = uni.getSystemInfoSync();

	webviewObj = plus.webview.create('', "webview", {
		plusrequire: "none", //禁止远程网页使用plus的API，有些使用mui制作的网页可能会监听plus.key，造成关闭页面混乱，可以通过这种方式禁止
		'uni-app': 'none', //不加载uni-app渲染层框架，避免样式冲突 
		popGesture:"close",
		top: systemInfo.statusBarHeight, //放置在titleNView下方。如果还想在webview上方加个地址栏的什么的，可以继续降低TOP值
		bottom: '0'
	})
	webviewObj.loadURL(options.url)
	// createShare()
}

// function createBtn() {
// 	let sys = uni.$u.sys()
// 	view = new plus.nativeObj.View('capsule', {
// 		top: sys.statusBarHeight + 7 + 'px',
// 		left: sys.screenWidth - 5 - 85 + 'px',
// 		height: '30px',
// 		width: '85px'
// 	});
// 	view.draw([{
// 			tag: 'rect',
// 			rectStyles: {
// 				color: '#C9C9C9',
// 				radius: '15px'
// 			},
// 			position: {
// 				top: '0',
// 				left: '0',
// 				width: '85px',
// 				height: '30px'
// 			}
// 		},
// 		{
// 			tag: 'rect',
// 			rectStyles: {
// 				color: 'rgba(255,255,255,1)',
// 				radius: '14px'
// 			},
// 			position: {
// 				top: '1px',
// 				left: '1px',
// 				width: '83px',
// 				height: '28px'
// 			}
// 		},
// 		{
// 			tag: 'img',
// 			src: '/static/icon/webgengduo.png',
// 			position: {
// 				top: '12px',
// 				left: '11px',
// 				width: '20px',
// 				height: '6px'
// 			}
// 		},
// 		{
// 			tag: 'rect',
// 			rectStyles: {
// 				color: '#C9C9C9'
// 			},
// 			position: {
// 				top: '4px',
// 				left: '42px',
// 				width: '1px',
// 				height: '22px'
// 			}
// 		},
// 		{
// 			tag: 'img',
// 			src: '/static/icon/webfanhui.png',
// 			position: {
// 				top: '6px',
// 				left: '55px',
// 				width: '18px',
// 				height: '18px'
// 			}
// 		},
// 	]);
// 	view.addEventListener("click", viewClick, false);
// }
async function viewClick(e) {
	if (e.clientX < 42) {
		nvMask.show()
		nvImageMenu.show() //5+应支持从底部向上弹出的动画
	} else if (e.clientX > 42) {
		webviewObj.hide();
		nvMask.hide()
		nvImageMenu.hide() //5+应支持从底部向上弹出的动画
		view.hide();
		if(!btnXuan){
			if(options.icon){
				try {
					const cachedMedia = await mediaCache.loadMedia(options.icon, 'avatar', 'image');
					btnOptions.url = cachedMedia
				} catch (error) {
					btnOptions.url = '_www/static/logo.png'
				}
			}else{
				btnOptions.url = '_www/static/logo.png'
			}
			btnXuan = initLevitatedSphere(btnOptions, clickHandler, true);
		}else{
			btnXuan.show()
		}
	}
}
function createShare() {
	var strShareUrl = options.url
	var screenWidth = plus.screen.resolutionWidth
	var margin = 25,
		iconWidth = 55,
		icontextSpace = 5,
		textHeight = 12
	var left1 = margin / 360 * screenWidth
	var iconSpace = (screenWidth - (left1 * 2) - (iconWidth * 4)) / 3 //屏幕宽度减去左右留白间距，再减去4个图标的宽度，就是3个同行图标的间距
	if (iconSpace <= 5) { //屏幕过窄时，缩小边距和图标大小，再算一次
		margin = 15
		iconWidth = 40
		left1 = margin / 360 * screenWidth
		iconSpace = (screenWidth - (left1 * 2) - (iconWidth * 4)) / 3 //屏幕宽度减去左右留白间距，再减去4个图标的宽度，就是3个同行图标的间距
	}
	var left2 = left1 + iconWidth + iconSpace
	var left3 = left1 + (iconWidth + iconSpace) * 2
	var left4 = left1 + (iconWidth + iconSpace) * 3
	var top1 = left1
	var top2 = top1 + iconWidth + icontextSpace + textHeight + left1
	nvMask = new plus.nativeObj.View("nvMask", { //先创建遮罩层
		top: '0px',
		left: '0px',
		height: '100%',
		width: '100%',
		backgroundColor: 'rgba(0,0,0,0.2)'
	});
	nvMask.addEventListener("click", () => { //处理遮罩层点击
		nvMask.hide();
		nvImageMenu.hide();
	})
	nvImageMenu = new plus.nativeObj.View("nvImageMenu", { //创建底部图标菜单
		bottom: '0px',
		left: '0px',
		height: '264px',
		width: '100%',
		backgroundColor: 'rgb(255,255,255)'
	});
	//绘制底部图标菜单的内容
	nvImageMenu.draw([{
			tag: 'rect', //菜单顶部的分割灰线
			color: '#e7e7e7',
			position: {
				top: '0px',
				height: '1px'
			}
		},
		{
			tag: 'font',
			id: 'sharecancel', //底部取消按钮的文字
			text: getApp().$t("common.cancelText"),
			textStyles: {
				size: '14px'
			},
			position: {
				bottom: '0px',
				height: '44px'
			}
		},
		{
			tag: 'rect', //底部取消按钮的顶部边线
			color: '#e7e7e7',
			position: {
				bottom: '45px',
				height: '1px'
			}
		},
		{
			tag: 'img',
			id: 'imgshuaxin',
			src: '/static/icon/webshuaxin.png',
			position: {
				top: top1,
				left: left1,
				width: iconWidth,
				height: iconWidth
			}
		},
		{
			tag: 'font',
			id: 'fontshuaxin',
			text: getApp().$t("common.refresh"),
			textStyles: {
				size: textHeight
			},
			position: {
				top: top1 + iconWidth + icontextSpace,
				left: left1,
				width: iconWidth,
				height: textHeight
			}
		},
		{
			tag: 'img',
			id: 'imgshare',
			src: '/static/icon/webguanbi.png',
			position: {
				top: top1,
				left: left2,
				width: iconWidth,
				height: iconWidth
			}
		},
		{
			tag: 'font',
			id: 'fontshare',
			text: getApp().$t("common.off"),
			textStyles: {
				size: textHeight
			},
			position: {
				top: top1 + iconWidth + icontextSpace,
				left: left2,
				width: iconWidth,
				height: textHeight
			}
		},
	])
	nvImageMenu.addEventListener("click", async(e) => { //处理底部图标菜单的点击事件，根据点击位置触发不同的逻辑
		if (e.screenY > plus.screen.resolutionHeight - 44) { //点击了底部取消按钮
			nvMask.hide();
			nvImageMenu.hide();
		} else if (e.clientX < 5 || e.clientX > screenWidth - 5 || e.clientY < 5) {
			//屏幕左右边缘5像素及菜单顶部5像素不处理点击
		} else { //点击了图标按钮
			var iClickIndex = -1 //点击的图标按钮序号，第一个图标按钮的index为0
			var iRow = e.clientY < (top2 - (left1 / 2)) ? 0 : 1
			var iCol = -1
			if (e.clientX < (left2 - (iconSpace / 2))) {
				iCol = 0
			} else if (e.clientX < (left3 - (iconSpace / 2))) {
				iCol = 1
			} else if (e.clientX < (left4 - (iconSpace / 2))) {
				iCol = 2
			} else {
				iCol = 3
			}
			if (iRow == 0) {
				iClickIndex = iCol
			} else {
				iClickIndex = iCol + 4
			}
			if (iClickIndex >= 0 && iClickIndex <= 5) {
				var strProvider = "",
					strScene = ""
				switch (iClickIndex) {
					case 0:
						webviewObj.loadURL(options.url)
						nvMask.hide();
						nvImageMenu.hide();
						break;
					case 1:
						if (webviewObj) {
							webviewObj.close();
							webviewObj = null; // Destroy the webviewObjnvMask
							options = null
							nvMask.close()
							nvMask = null
							nvImageMenu.close() //5+应支持从底部向上弹出的动画
							nvImageMenu = null
							view.close();
							view = null;
							btnXuan.close()
							btnXuan = null
						}
						break;
					case 2:

						break;
				}
			}
		}
	})
}
function clickHandler(res) {
	if (res.type == 'click') {
		btnXuan.hide()
		webviewObj.show();
		view.show();
	}
	if (res.type == 'move') {
		
		console.log('move', res);
	}
}